<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 新中天
 */
class XinztController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            case 3:
            case 4:
            case 17:
            case 18:
                $pay_bankcode = 'alipay.sqm.h5';
               break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $arr_data = [
            'method' => $pay_bankcode,
            'version' => '1.0',
            'nonce_str' => $this->_getRandomString(32),
            'mch_id' =>$this->config['mch_id'],
            'mch_order_no' => $return['orderid'],
            'body' => 'wlf',
            'cur_code' => 'CNY',
            'total_amount' => number_format($return['amount'],2,'.',''),
            'spbill_create_ip' => getIP(),
            'mch_req_time' => date('YmdHis'),
            'notify_url' => $return['notifyurl'],
            'sign_type' => 'MD5',
        ];

        ksort($arr_data);//根据键值升序排列
        $str_sign = httpstr($arr_data).$this->config['signkey'];
        $arr_data['sign'] = strtoupper(md5($str_sign));

         $arr_data['detail'] = '';
         $arr_data['attach'] = '';

         $res = curl_json($this->config['gateway'], $arr_data); //json提交

        $resp = json_decode($res,true);

        $code = $resp['code_url'];
        if(!$code){
            if($resp['return_msg']){
                $this->showmessage($resp['return_msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");
    }


    /**
     * 获取随机字符串
     * @param int $n 随机数的长度(默认32位)
     * @since 1.0
     * @return string
     */
    public  function _getRandomString($n = 32){
        $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//输出字符集
        $len = strlen($str) - 1;
        $s = '';
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }


    //通知
    public function notifyurl(){
        //$this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['47.112.221.175','47.244.189.248'])){
            exit("wrong2");
        }

        $p = json_decode(file_get_contents('php://input'),true);

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['mch_order_no'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据

        if($p['opstate'] === '0'){
            M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

                "pay_orderid_rd"=>htmlspecialchars($p['order_no']),
                "pay_true"=>$p['real_amount'],
            ));
        }else{
            M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

                "pay_orderid_rd"=>htmlspecialchars($p['order_no']),
            ));
        }

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['sign'];
        unset($p['sign']);
        unset($p['attach']);


        ksort($p);//根据键值升序排列
        $str_sign = httpstr($p).$this->config['signkey'];

        //生成签名
        $sign2 = strtoupper(md5($str_sign));

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['result_code'] !== 'SUCCESS'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],"SUCCESS");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
